const express = require('express');
const app = express();
app.listen(3000, () => { console.log('服务器已开启') });

// 引入模块 
const fs = require('fs');
const path = require('path')



// 开启session
const session = require('cookie-session');
app.use(session({
    keys: ['大大大萨达萨达']
}))

//验证码
const svg = require('svg-captcha');

app.get('/yzm1', (req, res) => {
    let captcha = svg.create();//创建验证码
    req.session.captcha = captcha.text;
    console.log(captcha.text);//{text:'验证码正确结果'，data：验证码svg图}
    res.type('svg')//设置mime类型为svg
    res.send(captcha.data)//把svg图响应出去
})



// post接参中间件
app.use(express.urlencoded({ extended: false }));
app.use(express.json())


//资源静态化
app.use(express.static(path.join(__dirname, 'view')))
//register渲染
app.get('/register', (req, res) => {
    res.sendFile(path.join(__dirname, 'view/register.html'))
})


app.post('/register', (req, res) => {
    // 接参
    let user = req.body;
    console.log(user);

    //JSON.stringify(user.photo).toLocaleLowerCase==JSON.stringify(req.session.captcha).toLocaleLowerCase


    //判断验证码正不正确
    if (user.photo.toUpperCase() !== req.session.captcha.toUpperCase()) {
        res.send({ code: 400, msg: '请输入正确验证码' })
    }

    // 获取persons.json数据
    let dir = path.join(__dirname, 'persons.json');
    let data = fs.readFileSync(dir, 'utf-8');
    data = JSON.parse(data);

    // 判断
    let s = data.find(item => item.username == user.username);

    if (s) {
        // 登录成功  存储用户信息  回应登录成功

        res.send({ code: 400, msg: '用户名被占用' })

    } else {
        data.push({ username: user.username, password: user.password, yzm: user.photo });
        fs.writeFileSync(dir, JSON.stringify(data));
        res.send({ code: 200, msg: '注册成功' })

    }

    // 
})

//判断验证码正不正确



